package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author huyong
 * @version 1.0.0
 * @description
 * @date 2015/5/29 17:56
 */
public class NIOClient {
	private InetSocketAddress inetSocketAddress;

	public NIOClient(String hostname, int port) {
		inetSocketAddress = new InetSocketAddress(hostname, port);
	}

	/**
	 * 发送请求数据
	 * @param requestData
	 */
	public void send(String requestData) {
		try {
			SocketChannel socketChannel = SocketChannel.open(inetSocketAddress);
			socketChannel.configureBlocking(false);
			ByteBuffer byteBuffer = ByteBuffer.allocate(512);
			socketChannel.write(ByteBuffer.wrap(requestData.getBytes()));

			while (true) {
				byteBuffer.clear();
				int readBytes = socketChannel.read(byteBuffer);
				if (readBytes > 0) {
					byteBuffer.flip();
					System.out.println("Client: readBytes = " + readBytes);
					System.out.println("Client: data = " + new String(byteBuffer.array(), 0, readBytes));
					socketChannel.close();
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String hostname = "localhost";
		String requestData = "32Actions speak louder than words!";
		int port = 9999;
		new NIOClient(hostname, port).send(requestData);
	}
}
